﻿@namespace MudBlazor.Docs.Examples

<MudCheckBox @bind-Checked="boolean">bool: @boolean</MudCheckBox>
<MudCheckBox @bind-Checked="nullable" Color="Color.Primary">bool?: @nullable</MudCheckBox>
<MudCheckBox @bind-Checked="integer" Color="Color.Secondary">int: @integer</MudCheckBox>
<MudCheckBox @bind-Checked="str" Color="Color.Tertiary">string: "@(str)"</MudCheckBox>
<MudCheckBox @bind-Checked="customstr" Converter="@(new CustomStringToBoolConverter())"> custom string: "@(customstr)"</MudCheckBox>
<MudCheckBox @bind-Checked="obj" Converter="@(new ObjectToBoolConverter())">boxed bool: "@(obj.ToString())"</MudCheckBox>

@code{ 
    public bool boolean { get; set; } = true;
    public bool? nullable { get; set; } = true;
    public int integer { get; set; } = 1;
    public string str { get; set; } = "on";
    public string customstr { get; set; } = CustomStringToBoolConverter.NullString;
    public object obj { get; set; } = false;

    public class ObjectToBoolConverter : BoolConverter<object>
    {
        public ObjectToBoolConverter()
        {
            SetFunc = OnSet;
            GetFunc = OnGet;
        }

        private object OnGet(bool? value) => value == true;

        private bool? OnSet(object arg)
        {
            if (arg == null)
                return null;
            try
            {
                if (arg is bool)
                    return (bool)arg;
                else if (arg is bool?)
                    return (bool?)arg;
                else
                {
                    UpdateSetError("Unable to convert to bool? from type object");
                    return null;
                }
            }
            catch (FormatException e)
            {
                UpdateSetError("Conversion error: " + e.Message);
                return null;
            }
        }
    }

    public class CustomStringToBoolConverter : BoolConverter<string>
    {
        public CustomStringToBoolConverter()
        {
            SetFunc = OnSet;
            GetFunc = OnGet;
        }

        public const string TrueString = "Yes, please";
        public const string FalseString = "No, thanks";
        public const string NullString = "I don't know";

        private string OnGet(bool? value) => value == null ? NullString : (value == true ? TrueString : FalseString);

        private bool? OnSet(string arg)
        {
            try
            {
                if (arg == TrueString)
                    return true;
                if (arg == FalseString)
                    return false;
                return null;
            }
            catch (FormatException e)
            {
                UpdateSetError("Conversion error: " + e.Message);
                return null;
            }
        }
    } }